/* gearserial.c -- Arquivo da bilbioteca para enviar comandos pela
 * serial
 *
 * Copyright (C) 2007, Diogo F. S. Ramos <diogofsr at gmail.com>
 * GEAR - Grupo de Estudos Avançados em Robótica
 * <http://www.sel.eesc.usp.br/gear>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <termios.h>

#include "xmalloc.h"
#include "xerror.h"
#include "gearserial.h"


/* Prototypes */
static float gearserial_exp( float base, int elev );
static void gearserial_insert_checksum( GearSerial *self, const char *message );

GearSerial*
gearserial_new( void )
{
    GearSerial *self = XMALLOC(GearSerial, 1);

    self->end_serial = NULL;
    self->fd = -1;
    self->sleep_time.tv_sec = 0;
    self->sleep_time.tv_nsec = 1000000;
    self->many_times = 10;
    self->serial_saved_atributes = NULL;
    self->message_size = 7;
    self->checksum_size = 0;
    self->package_size = 0;
    self->package = NULL;
    gearserial_set_size_package( self,
				 7 );
    self->baud_rate = B115200;
    self->boo_two_stop_bits = 0;
    self->boo_parity_bit = 0;
    self->boo_parity_odd = 0;

    return self;
}

void
gearserial_set_size_package( GearSerial *self,
			     const int size )
{
    int i = 0;
    int checksum = 0;
    self->message_size = size;
    
    while( self->message_size > checksum )
    {
	checksum += gearserial_exp(16,2*i);
	i++;
    }
    self->checksum_size = i;

    if( self->package != NULL )
	XFREE( self->package );

    self->package_size = self->checksum_size +self->message_size;

    self->package = XMALLOC( unsigned char,
			     self->package_size );

}

static float
gearserial_exp( float base,
		int elev )
{
    int i = 0;
    float res = 1;

    if( elev == 0 )
	return 1;

    for( i = 0 ; i < elev ; i++ )
    {
	res *= base;
    }
    
    return res;
}

void
gearserial_send( GearSerial *self,
		 const char *str )
{
    int i = 0;    
    struct timespec rem;
    const unsigned char *pack = NULL;
    int bytes_sent = 0;

    
    pack = gearserial_pack( self,
			    str );

    for( i = 0 ; i < self->many_times ; i++ )
    {
	bytes_sent = write( self->fd, pack, self->package_size );
	
	if( bytes_sent == -1 )
	    xerror_error("Pacote nao enviado");
	
	nanosleep( &(self->sleep_time), &rem );
    }
	
}

const unsigned char *
gearserial_pack( GearSerial *self,
		 const char *message )
{
    int i = 0;
    unsigned char * message2 = (unsigned char *) message;

    for( i = 0 ; i < self->message_size ; i++ )
    {
	self->package[i] = message2[i];
    }
    gearserial_insert_checksum( self,
				message );

    return self->package;
}

static void
gearserial_insert_checksum( GearSerial *self,
			    const char *message )
{
    int i = 0;
    unsigned long int soma = 0;
    const unsigned char *message2 = (unsigned char*) message;
    
    for( i = 0 ; i < self->message_size ; i++ )
    {
	soma += message2[i];
    }

    for( i = 0 ; i < self->checksum_size ; i++ )
    {
	soma = soma >> (8*i);
	self->package[self->package_size-i-1] = soma;
    }

}
		     
void
gearserial_destroy( GearSerial *self )
{
    if (tcsetattr(self->fd, TCSANOW, self->serial_saved_atributes ) != 0)
	xerror_error("Nao voltei as configuracoes da serial");
    
    XFREE( self->end_serial );
    XFREE( self->serial_saved_atributes );

    XFREE( self );
}

int
gearserial_open_serial( GearSerial *self,
			const char *path )
{
    self->end_serial = XMALLOC( char, strlen(path) + 1 );
    strcpy( self->end_serial, path );
    self->fd = open(self->end_serial, O_RDWR | O_NOCTTY | O_NDELAY);
    if( self->fd == -1 )
    {
	xerror_error("Nao consegui abrir a serial");
	xerror_error(path);
	return EXIT_FAILURE;
    }
    
    if( gearserial_conf_serial( self ) == EXIT_FAILURE )
	xerror_fatal("Nao configurei a serial");
    
    return EXIT_SUCCESS;
}

int
gearserial_conf_serial( GearSerial *self )
{
    struct termios term;

    /* save current settings */
    if( self->serial_saved_atributes == NULL )
    {
	self->serial_saved_atributes = XMALLOC( struct termios,
						1 );
	if (tcgetattr(self->fd, self->serial_saved_atributes ) != 0)
	{
	    xerror_error("Nao pude salvar os atributos da serial");
	    return EXIT_FAILURE;
	}
    }

    /* get current settings */
    if (tcgetattr(self->fd, &(term) ) != 0)
    {
	xerror_error("Nao pude pegar os atributos da serial");
	return EXIT_FAILURE;
    }

    
    /* set speed */
    if (cfsetispeed (&term, self->baud_rate) != 0)
    {
	xerror_error("Nao pude setar a velocidade de entrada");
	return EXIT_FAILURE;
    }
    if (cfsetospeed (&term, self->baud_rate) != 0)
    {
	xerror_error("Nao pude setar a velocidade de saida");
	return EXIT_FAILURE;
    }
    
    if( self->boo_two_stop_bits )
	term.c_cflag |= CSTOPB;
    if( self->boo_parity_bit )
	term.c_cflag |= PARENB;
    if( self->boo_parity_odd )
	term.c_cflag |= PARODD;

    term.c_cflag |= CS8;

    /* set terminal attributes */
    if (tcsetattr(self->fd, TCSANOW, &term) != 0)
    {
	xerror_error("Nao pude setar os atributos do termios");
	return EXIT_FAILURE;
    }

    
    return EXIT_SUCCESS;
}
